using UnityEngine;

namespace skeleton
{
    public class ChaseState : State
    {
        [SerializeField] float speed;
        [SerializeField] Transform player;
        [SerializeField] float maxChaseDistance;
        [SerializeField] float maxChaseDuration;

        float timer;

        // ========================================================================

        public override bool Check() => base.Check() && (skeleton.PlayerDetected() || WithinAttackRange());

        public override void Process()
        {
            base.Process();

            var hitPoint = skeleton.PlayerDetected();
            if (hitPoint)
            {
                timer = maxChaseDuration;
                if (hitPoint.distance <= skeleton.GetAttackRange() && skeleton.TryChangeState(StateCode.Attack)) return;
            }
            else
            {
                timer -= Time.deltaTime;
                if (timer < 0 || OutOfChaseRange())
                    skeleton.ChangeState(StateCode.Idle);
            }

            if (player.position.x < skeleton.transform.position.x)
                skeleton.SetVelocity(-speed, skeleton.GetVelocity(1));
            else if (player.position.x > skeleton.transform.position.x)
                skeleton.SetVelocity(speed, skeleton.GetVelocity(1));
        }

        // ========================================================================
        private float DistanceToPlayer() => Vector2.Distance(player.position, skeleton.transform.position);
        private bool WithinAttackRange() => DistanceToPlayer() < skeleton.GetAttackRange();
        private bool OutOfChaseRange() => DistanceToPlayer() > maxChaseDistance;
    }
}
